/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yufei.toolinterface;

import java.util.ArrayList;
import java.util.List;

import com.yufei.infoExtractor.core.InfoExtractorMI;
import com.yufei.infoExtractor.core.impl.InfoExtractorM;
import com.yufei.infoExtractor.pfw.entity.Task;
import com.yufei.infoExtractor.util.AppUtil;
import com.yufei.infoExtractor.util.CommonUtil;
import com.yufei.toolinterface.util.DialogUtil;

/**
 *
 * @author jasstion
 */
public class TaskAddDialog extends javax.swing.JDialog {
	private InfoExtractorMI infoExtractorMI=(InfoExtractorMI) AppUtil.getBeanFromBeanContainer(InfoExtractorM.class);
    private TaskMPanel taskMPanel=null;
    /**
     * Creates new form TaskAddDialog
     */
    public TaskAddDialog(javax.swing.JFrame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        taskMPanel=(TaskMPanel) parent;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        keyWordsLable = new javax.swing.JLabel();
        keyWords = new javax.swing.JTextField();
        taskAddButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        selfStartRadioButton = new javax.swing.JRadioButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("添加任务");

        keyWordsLable.setText("关键字");

       


        taskAddButton.setText("创建");
        taskAddButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                taskAddButtonActionPerformed(evt);
            }
        });

        jScrollPane1.setHorizontalScrollBar(null);

        jTextArea1.setEditable(false);
        jTextArea1.setColumns(20);
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(5);
        jTextArea1.setText("任务名称表示此次查询任务的名称，方面查询；\n关键字表示此次要查询的相关网页关联的关键字，比如：google查询java spring的时候，你会输入java spring,表示你想查询出与java以及spring相关的网页内容；如果你想同一个任务返回两种关键字相关的查询的话，中间以@隔开，比如你现在命名一个健康名称的任务，你想同时查询高‘高血压 死亡’以及‘饮食 健康’那么你应该这样输入：高血压 死亡@饮食 健康\n批量创建任务：\n如果你觉得一个一个的创建任务很麻烦的话，你可以按照下列方式一次操作创建多个任务：\n每个任务关键词之间以#隔开，比如你想创建三个关键词查询任务：周杰伦,习近平以及Hibernate，那么你按照上述规则组成一个字符串然后填入关键字对应的输入框中，比如：周杰伦#习近平#Hibernate，然后点击创建，你就会在任务列表中状态为未启动的列表中查询到你新创建的三个任务。\n另外你也可以选择是否自动启动任务的运行，如果你需要在创建任务成功之后立即自动启动任务那么你在创建之前勾选上自动运行按钮。");
        jScrollPane1.setViewportView(jTextArea1);

        selfStartRadioButton.setText("自动启动");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(keyWordsLable, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(205, 205, 205)
                        .addComponent(taskAddButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addComponent(keyWords, javax.swing.GroupLayout.PREFERRED_SIZE, 481, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(289, 289, 289)
                .addComponent(selfStartRadioButton)
                .addGap(0, 0, Short.MAX_VALUE))
            .addComponent(jScrollPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(keyWordsLable)
                    .addComponent(keyWords, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(selfStartRadioButton)
                .addGap(60, 60, 60)
                .addComponent(taskAddButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

  

    private void taskAddButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_taskAddButtonActionPerformed
        // TODO add your handling code here:
    
    	String keywords1=keyWords.getText();
    	if(CommonUtil.isEmptyOrNull(keywords1)){
    		DialogUtil.popUpDialog("查询关键字不能为空！");
    		return;

    	}
    	boolean isSelfStarted=this.selfStartRadioButton.isSelected();
    	String[] taskKeywords=keywords1.split("#");
		List<String> keywordList=null;
		String taskName=null;
		List<Task> tasks=new ArrayList();
		Task task=null;
    	for(int i=0;i<taskKeywords.length;i++){
    		keywordList=new ArrayList<String>();
        	String[] tempStrs=taskKeywords[i].split("@");
        	for(String str:tempStrs){
            	keywordList.add(str);

        	}
        	taskName= taskKeywords[i].trim();
			Task tempTask=infoExtractorMI.queryEntityByPropertyValue("taskName", taskName, Task.class);
        	if(tempTask!=null){
        	DialogUtil.popUpDialog("名称为：'"+taskName+"'已存在，请重新选择名称!");
           return;
        	}
        	task=	infoExtractorMI.createTask(taskName, keywordList);
             taskMPanel.addTaskTotaskListPanel(task);
             tasks.add(task);
            
             
    	}
    	
    	
    DialogUtil.popUpDialog("创建成功！");
    if(isSelfStarted){
      	taskMPanel.selfStartBatchTasks(tasks);
    }
    taskMPanel.refreshTaskList();
   

    }//GEN-LAST:event_taskAddButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TaskAddDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TaskAddDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TaskAddDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TaskAddDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                TaskAddDialog dialog = new TaskAddDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField keyWords;
    private javax.swing.JLabel keyWordsLable;
    private javax.swing.JRadioButton selfStartRadioButton;
    private javax.swing.JButton taskAddButton;
    // End of variables declaration//GEN-END:variables
}
